package com.ds.event;


import com.alibaba.fastjson2.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionalEventListener;

/**
 * @class: UserListener
 * @description:
 * @author: fs
 * @create: 2023/10/13 9:44
 **/
@Slf4j
@Component
@RequiredArgsConstructor
public class UserListener {
    //  private final RocketMQTemplate rocketMQTemplate;

    @Async
    @EventListener(UserEvent.class)
    public void listener(UserEvent event) {
        User user = event.getUser();
        log.info("普通监听 = " + JSONObject.toJSONString(user));
    }


    @Async
    // 事务监听 默认事务提交后执行     fallbackExecution 没有事务提交是否执行
    @TransactionalEventListener(classes = UserEvent.class, fallbackExecution = true)
    public void transactionalListener(UserEvent event) {
        User user = event.getUser();
        log.info("事务监听 = " + JSONObject.toJSONString(user));
    }

    //@Async
    //@TransactionalEventListener(classes = UserEvent.class, fallbackExecution = true)
    //public void sendMq(UserEvent event) {
    //    User user = event.getUser();
    //    MessageHeaderAccessor accessor = new MessageHeaderAccessor();
    //    accessor.setHeader(TraceIdConstant.TRACE_ID, MDC.get(TraceIdConstant.TRACE_ID));
    //    Message<User> msg = MessageBuilder.withPayload(user).setHeaders(accessor).build();
    //    rocketMQTemplate.syncSend("test", msg);
    //    log.info("发送给mq = " + JSONObject.toJSONString(user));
    //}
}
